package com.core.safe;

import com.core.comment.StringUtil;

import java.awt.geom.FlatteningPathIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MySubject {
    private static volatile Map<String, MySubject> subMap = new ConcurrentHashMap<>();
    private String token;

    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public static synchronized MySubject getInstance(String ip) {
        MySubject mySubject = subMap.get(ip);

        if (mySubject == null) {
            synchronized (MySubject.class) {
                mySubject = new MySubject();
                mySubject.setIp(ip);
                subMap.put(ip, mySubject);
            }
        }
        return mySubject;
    }

    public String login(UserToken userToken) {
        AuthRealm authRealm = SafeCache.getAuthRealm();
        SafeUserInfo userInfo = authRealm.doGetSafeUserInfo(userToken);
        if (userInfo == null) {
            throw new RuntimeException("登录密码错误");
        }
        token = SafeCache.addUser(userInfo);
        userInfo.setToken(token);
        SafeOterInfo roleInfo = authRealm.doGetSafeOterInfo(userInfo.getUser());
        SafeCache.addUserRole(token, roleInfo);
        return token;
    }

    public boolean valid(String token) {
        boolean v = false;
        SafeUserInfo user = SafeCache.getUser(token);
        if (user != null) v = true;
        if (user != null && !v && token.equals(user.getToken())) v = true;
        return v;
    }

    public boolean validUrl(String token, String url) {
        boolean v = false;
        if (valid(token)) {
            SafeOterInfo role = SafeCache.getUserRole(token);
            for (String canUrl : role.getResourceList()) {
                if (canUrl.equals(url)) {
                    v = true;
                    break;
                }
            }
        }
        return v;
    }

    public boolean isLogUrl(String url) {
        boolean v = false;
        String loginUrl = SafeCache.getFilter().getLogUrl();
        if (StringUtil.isNotBlack(loginUrl)) {
            if (loginUrl.equals(url)) v = true;
        }
        return v;
    }
}
